import React from 'react'
import { getRandomNumbers } from '../../../utils/math'

class KunKunGame extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      dataSource: [],
      toolCard: [],
      cardInBox: [],
    }
    this.rowSize = window.screen.width / 20 // 图片边长的一半
    this.rowNum = 12
    this.colNum = 14
    this.levelNum = 6
    this.levelCardNum = 20
    this.toolNum = 10
    this.types = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    this.eachTypeNum = 12
    this.maxCardInBox = 7
    this.idArray3D = [] // 可修改，重新初始化时要注意清空
  }

  componentDidMount() {
    this.initCards()
  }

  // 初始化，共120张图片，6层，每层20张。10类图案，每类12张
  initCards = () => {
    let currentId = 0 // 用于自增id
    this.idArray3D = []
    let newDataSource = []
    // 生成随机顺序的图片类型数组typeArr
    const filteredTypeIndexs = getRandomNumbers(
      0,
      this.levelCardNum * this.levelNum - 1,
      this.levelCardNum * this.levelNum
    )
    const allTypes = new Array(this.eachTypeNum).fill([...this.types]).flat()
    const typeArr = new Array(this.levelCardNum * this.levelNum).fill('').map((_, index) => {
      return allTypes[filteredTypeIndexs[index]]
    })
    // 按level，每层生成20个图片, row、col随机但不重复, 单数层row、col为双数，双数层row、col为单数
    for (let level = 1; level <= this.levelNum; level += 1) {
      const filteredIndexs = getRandomNumbers(
        0,
        (this.rowNum / 2) * (this.colNum / 2) - 1,
        this.levelCardNum
      )
      const tmp = new Array(this.rowNum / 2).fill(new Array(this.colNum / 2).fill(''))
      // eslint-disable-next-line no-loop-func
      tmp.forEach((row, rowIndex) => {
        row.forEach((_, colIndex) => {
          if (filteredIndexs.includes(rowIndex * (this.colNum / 2) + colIndex)) {
            currentId += 1
            newDataSource.push({
              id: currentId,
              type: typeArr.pop(),
              level,
              row: (level % 2) + rowIndex * 2,
              col: (level % 2) + colIndex * 2,
            })
          }
        })
      })
    }

    // 从dataSource中随机挑选出10张当作道具
    const toolIds = getRandomNumbers(1, this.levelCardNum * this.levelNum, this.toolNum)
    const toolCard = newDataSource.filter((i) => toolIds.includes(i.id))
    newDataSource = newDataSource.filter((i) => !toolIds.includes(i.id))

    // 用三维数组存储id, 来确定哪些卡片不置灰
    new Array(this.levelNum).fill('').forEach((_, index) => {
      const level = index + 1
      const arr = Array.from({ length: this.rowNum }, () => new Array(this.colNum).fill(''))
      newDataSource
        .filter((i) => i.level === level)
        .forEach((item) => {
          arr[item.row][item.col] = item.id
        })
      this.idArray3D.push(arr)
    })
    this.addDisabledProp(newDataSource, this.idArray3D)
    this.setState({
      dataSource: newDataSource,
      toolCard,
      cardInBox: [],
    })
  }

  // 设置disabled
  addDisabledProp = (dataSource, idArray3D) => {
    dataSource.forEach((item) => {
      item.disabled = false
      if (item.level >= this.levelNum) return
      for (let z = item.level; z <= this.levelNum - 1; z += 1) {
        for (
          let x = Math.max(0, item.row - 1);
          x <= Math.min(this.rowNum - 1, item.row + 1);
          x += 1
        ) {
          for (
            let y = Math.max(0, item.col - 1);
            y <= Math.min(this.colNum - 1, item.col + 1);
            y += 1
          ) {
            if (idArray3D[z][x][y]) {
              item.disabled = true
              // 跳出循环
              z = this.levelNum - 1
            }
          }
        }
      }
    })
  }

  // 图片被选中
  onSelectCard = (selectedItem) => {
    if (selectedItem.disabled) return
    const { dataSource, toolCard, cardInBox } = this.state
    const newDataSource = []
    const newToolCard = [...toolCard]

    let newCardInBox = JSON.parse(JSON.stringify(cardInBox))

    dataSource.forEach((item) => {
      // 中心区被没选中的
      if (item.id !== selectedItem.id) {
        newDataSource.push(item)
      }
      // 中心区被选中的
      else {
        this.idArray3D[item.level - 1][item.row][item.col] = ''
      }
    })
    // 从道具区选中的
    if (toolCard.length && selectedItem.id === toolCard[toolCard.length - 1].id) {
      newToolCard.pop()
    }

    // cardInBox相同的type要放到一起，超过三个则消除，且最多只能放maxCardInBox张
    const sameTypeIndex = newCardInBox.findIndex((i) => i.type === selectedItem.type)
    const sameTypeCards = newCardInBox.filter((i) => i.type === selectedItem.type)
    // 消除
    if (sameTypeCards.length >= 2) {
      newCardInBox = [
        ...newCardInBox.slice(0, sameTypeIndex),
        ...newCardInBox.slice(sameTypeIndex + 2),
      ]
    }
    // 插入到相同type卡片的位置
    else if (sameTypeIndex >= 0) {
      newCardInBox = [
        ...newCardInBox.slice(0, sameTypeIndex),
        selectedItem,
        ...newCardInBox.slice(sameTypeIndex),
      ]
    }
    // 没有类型相同的则放到最右边
    else {
      newCardInBox = [...newCardInBox, selectedItem]
    }

    // 调整不置灰的卡片
    this.addDisabledProp(newDataSource, this.idArray3D)

    this.setState(
      {
        dataSource: newDataSource,
        cardInBox: newCardInBox,
        toolCard: newToolCard,
      },
      () => {
        // 判断游戏成功
        if (newDataSource.length === 0 && newToolCard.length === 0) {
          alert('您已加入羊群！')
          this.initCards()
        }
        // 判断游戏失败
        else if (Object.values(newCardInBox).flat().length === this.maxCardInBox) {
          alert('游戏失败')
          this.initCards()
        }
      }
    )
  }

  render() {
    const xnyPic = (
      <img
        alt=""
        src=""
        width="100%"
        height="100%"
      />
    )

    const linkCatPic = (
      <img
        src=""
        alt=""
        width="100%"
        height="100%"
      />
    )

    const pic01 = (
      <img
        alt=""
        src="http://csc-data.oss-cn-shenzhen.aliyuncs.com/resource/Group%2016%402x_681530256615673856.png"
        width="100%"
        height="100%"
      />
    )

    const pic02 = (
      <img
        alt=""
        src="http://csc-data.oss-cn-shenzhen.aliyuncs.com/oss/Group%2022%402x_570969776973811712.png"
        width="100%"
        height="100%"
      />
    )

    const pic03 = (
      <img
        alt=""
        src="http://csc-data.oss-cn-shenzhen.aliyuncs.com/oss/Group%2014%402x_571035345567748096.png"
        width="100%"
        height="100%"
      />
    )

    const pic04 = (
      <img
        alt=""
        src="http://csc-data.oss-cn-shenzhen.aliyuncs.com/oss/LOGO_582535697102147584.jpg"
        width="100%"
        height="100%"
      />
    )

    const pic05 = (
      <img
        alt=""
        src="http://csc-data.oss-cn-shenzhen.aliyuncs.com/oss/Group%2019%281%29_576774177747505152.png"
        width="100%"
        height="100%"
      />
    )

    const pic06 = (
      <img
        alt=""
        src="http://csc-data.oss-cn-shenzhen.aliyuncs.com/oss/Group%2030_603912322041384960.png?Expires=3140825517&amp;OSSAccessKeyId=LTAIpIZLQzIhzcWX&amp;Signature=lMLe%2FyvjJBBDTUwp%2FOUIW07LWXU%3D"
        width="100%"
        height="100%"
      />
    )

    const pic07 = (
      <img
        alt=""
        src="http://csc-data.oss-cn-shenzhen.aliyuncs.com/resource/%E9%93%B6%E4%BC%81%E7%9B%B4%E8%BF%9E%402x_646194203851886592.png?Expires=3150906303&amp;OSSAccessKeyId=LTAIpIZLQzIhzcWX&amp;Signature=vYal%2Fo4NhBZIVLGxXOQfqI9tQAw%3D"
        width="100%"
        height="100%"
      />
    )

    const pic08 = (
      <img
        alt=""
        src="http://csc-data.oss-cn-shenzhen.aliyuncs.com/resource/depotAccountList_953321299458002944_957635500057956352.png"
        width="100%"
        height="100%"
      />
    )

    const images = [pic01, pic02, pic03, pic04, pic05, pic06, pic07, pic08, xnyPic, linkCatPic]

    const { dataSource, toolCard, cardInBox } = this.state

    const { rowSize, colNum, rowNum } = this

    return (
      <>
        {/* <h1>Kun le ge Kun Game</h1> */}
        <h1>Game of wzs</h1>
        <div>
          {/* 行数：{this.rowNum / 2} <br />
          列数：{this.colNum / 2} <br /> */}
          层数：{this.levelNum} <br />
          {/* 类型数：{this.types.length} <br /> */}
          {/* 道具图片数：{this.toolNum} <br /> */}
          图片总数：{this.levelCardNum * this.levelNum} <br />
          坑位：{this.maxCardInBox} <br />
          难度：随机 <br /> <br />
        </div>
        <div
          style={{
            position: 'relative',
            left: '50%',
            marginLeft: -(rowSize * colNum) / 2 - 20,
            border: '1px solid #ddd',
            // boxSizing: 'border-box',
            padding: '10px',
            width: rowSize * (colNum + 1),
            height: rowSize * (rowNum + 1),
          }}
        >
          {dataSource.map((item) => (
            <div
              key={item.id}
              style={{
                position: 'absolute',
                left: rowSize * item.col + 10,
                top: rowSize * item.row + 10,
                zIndex: item.level,
              }}
              onKeyUp={() => {}}
              onClick={() => this.onSelectCard(item)}
            >
              <div
                style={{
                  width: rowSize * 2,
                  height: rowSize * 2,
                  boxSizing: 'border-box',
                  backgroundColor: 'white',
                  filter: item.disabled ? 'grayscale(95%)' : 'grayscale(0)',
                  border: '1px solid #ddd',
                  borderRadius: '5px',
                  padding: '5px',
                }}
              >
                {images[item.type]}
              </div>
            </div>
          ))}
          {toolCard.map((item, index) => (
            <div
              key={item.id}
              style={{
                position: 'absolute',
                left: 5 * index,
                bottom: -rowSize * 3,
                zIndex: item.level,
              }}
              onKeyUp={() => {}}
              onClick={() => this.onSelectCard(item)}
            >
              <div
                style={{
                  width: rowSize * 2,
                  height: rowSize * 2,
                  boxSizing: 'border-box',
                  backgroundColor: 'white',
                  border: '1px solid #ddd',
                  borderRadius: '5px',
                  padding: '5px',
                }}
              >
                {images[item.type]}
              </div>
            </div>
          ))}
          <div
            style={{
              position: 'absolute',
              border: '1px solid #ddd',
              left: 0,
              bottom: -rowSize * 6,
              width: rowSize * 2 * this.maxCardInBox,
              height: rowSize * 2,
            }}
          >
            {cardInBox.map((item, index) => (
              <div
                key={item.id}
                style={{
                  position: 'absolute',
                  left: rowSize * 2 * index,
                  top: 0,
                }}
              >
                <div
                  style={{
                    width: rowSize * 2,
                    height: rowSize * 2,
                    boxSizing: 'border-box',
                    backgroundColor: 'white',
                    border: '1px solid #ddd',
                    borderRadius: '5px',
                    padding: '5px',
                  }}
                >
                  {images[item.type]}
                </div>
              </div>
            ))}
            {/* 留白 */}
            <div
              style={{
                width: 10,
                height: '20px',
                position: 'absolute',
                left: 0,
                top: rowSize * 4,
              }}
            />
          </div>
        </div>
      </>
    )
  }
}

export default KunKunGame
